<template>
    <div>
        <table border="1" align="center" width="400px">
            <thead>
                <th id="biaoti" colspan="4">
                    <h2>购物车</h2>
                </th>
            </thead>
                <tbody>
                <tr align="center">
                    <td>货名</td>
                    <td>单价</td>
                    <td>数量</td>
                    <td>合计</td>
                </tr>
                <tr align="center" v-for="(user, index) in package1" :key="index">
                    <td>{{ user.name }}</td>
                    <td>{{ user.price }}</td>
                    <td>
                        <button @click="sub(index)">-</button>
                        {{ user.count }}
                        <button @click="add(index)">+</button>
                    </td>
                    <td>{{ user.price * user.count }}</td>
                </tr>
                <tr align="center">
                    <td colspan="3">总计</td>
                    <td>{{ total }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
import { reactive, toRefs, computed } from 'vue'

export default {
    setup() {
        const state = reactive({
            package1: [
                {
                    name: '华为mate30',
                    price: 4566,
                    count: 2
                },
                {
                    name: '华为mate40',
                    price: 4166,
                    count: 3
                },
                {
                    name: '苹果X',
                    price: 5200,
                    count: 2
                },
                {
                    name: 'OPPO',
                    price: 2180,
                    count: 4
                }
            ]
        })
        const sub = (index) => {
            if (state.package1[index].count > 0) {
                state.package1[index].count--
            }
        }
        const add = (index) => {
            state.package1[index].count++
        }
        const total = computed(() => {
            let sum = 0
            for (let i = 0; i < state.package1.length; i++) {
                sum += state.package1[i].price * state.package1[i].count
            }
            return sum
        })
        return {
            ...toRefs(state),
            sub,
            add,
            total
        }
    }
}
</script>

<style scoped>
#biaoti{
    color:aquamarine;
}
</style>